﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace YJKRevitKernel.SampleAndTest.HalfNSquareSupportTest
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdCreateRandomCurve : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Document document = commandData.Application.ActiveUIDocument.Document;
			List<Curve> list = CmdCreateRandomCurve.CreateRandomCurve(document, 1000, 200.0, 800.0);
			using (Transaction transaction = new Transaction(document, "create modelCurve"))
			{
				transaction.Start();
				foreach (Curve curve in list)
				{
					document.Create.NewModelCurve(curve, document.ActiveView.SketchPlane);
				}
				transaction.Commit();
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private static List<Curve> CreateRandomCurve(Autodesk.Revit.DB.Document useDoc, int nCount, double dMin = -100.0, double dMax = 100.0)
		{
			List<XYZ> list = new List<XYZ>();
			for (int i = 0; i < nCount * 2; i++)
			{
				list.Add(CmdCreateRandomCurve.CreatRandomPoint(dMin, dMax));
			}
			List<Curve> list2 = new List<Curve>();
			using (Transaction transaction = new Transaction(useDoc, "creat curve"))
			{
				transaction.Start();
				while (list.Count >= 2)
				{
					XYZ xyz = list.First<XYZ>();
					list.RemoveAt(0);
					XYZ xyz2 = list.First<XYZ>();
					list.RemoveAt(0);
					try
					{
						Curve item = Line.CreateBound(xyz, xyz2);
						list2.Add(item);
					}
					catch (Exception)
					{
					}
				}
				transaction.Commit();
			}
			return list2;
		}

		private static XYZ CreatRandomPoint(double dMax, double dMin)
		{
			List<double> list = new List<double>();
			for (int i = 0; i < 3; i++)
			{
				list.Add(CmdCreateRandomCurve.CreatRandom(dMax, dMin));
			}
			return new XYZ(list.ElementAt(0), list.ElementAt(1), 0.0);
		}

		private static double CreatRandom(double dMax, double dMin)
		{
			return new Random(Guid.NewGuid().GetHashCode()).NextDouble() * (dMax - dMin) + dMin;
		}
	}
}
